program tabgenlabel 

syntax varname [if] [in]

marksample touse , strok
 
	* tabulates var, generating one binary variable 
	* for each value of varname 
	************************************************
		tab `1' if `touse' , gen(`1') 
 
	* local with list of each distinct value of varname 
	* stored in `levels' 
	****************************************************
	qui: levelsof `1' if `touse' , local(levels) 

	* local with the label name attached to varname 
	************************************************
	local valuelabel: value label `1' 
	
	
	* rename the variables created in tabgen 
	* (numbering starts at 1) 
	*****************************************
	local i = 0 
	foreach level of local levels {
	local i = `i'+1 
	
		* if no label attached to varname 
		* then varname must be string 
		* and created vars will be named 
		* the corresponding string value 
		**********************************
			if "`valuelabel'"=="" { 
				local indvaluelabel `level' 
			}
			di "`indvaluelabel'" 
			
		* if there is a label attached to varname 
		* then name created vars according to value label
		**************************************************
			else{ 
				local indvaluelabel: label `valuelabel' `level', strict
			}
			di "`indvaluelabel'" 
	
	ren `1'`i' `indvaluelabel' 
}

end 
